package com.adcc.loadsheet.billing.security;

import com.adcc.loadsheet.billing.configuration.SystemConfig;
import com.adcc.loadsheet.billing.vo.ResultVO;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 调用登录请求成功后的业务处理接口
 * Created by zhaoml on 2020-04-01.
 */
@Component
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    SystemConfig systemConfig;

    @Autowired
    private JWTFactory jwtFactory;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        ResultVO vo = new ResultVO();
        try{
            UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
            BillingUserDetails user = (BillingUserDetails)authenticationToken.getPrincipal();
            BillingUserToken sct = new BillingUserToken();
            sct.setBody(user.getUsername());
            DateTime curTime = DateTime.now(DateTimeZone.UTC);
            DateTime expiredTime = curTime.plusHours(systemConfig.getTokenExpiredTime());
            sct.setExpiredTime(expiredTime);
            //String token = systemConfig.getTokenPrefix() + " " + jwtFactory.encode(sct);
            String token = systemConfig.getTokenPrefix()  + jwtFactory.encode(sct);

            response.addCookie(CookieUtil.setCookie("loadsheetbilltoken",token,-1,"",true));
            vo.setData(null);
        }catch (Exception ex){
            throw new NullPointerException("encode token error");
        }
        response.getWriter().write(JSON.toJSONString(vo));
    }
}